import React, {useRef} from 'react'
import { Card, Form, Button, Radio, DatePicker, Table, Space, Image, Tag, Popconfirm, message} from 'antd'
import styles from './index.module.scss'
import { Breadcrumb } from 'antd'
import { Link } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { useEffect } from 'react'
import { getArticles, delArticle } from '@/store/actions/article.js'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import defaultImg from '@/assets/error.png'
import { COLORS, STATUS } from '@/constants'
import { useHistory } from 'react-router-dom'
import MyChannels from '@/components/MyChannels'
const { RangePicker } = DatePicker
export default function Article() {
  
  const history = useHistory()
  const dispatch = useDispatch()
  const {total_count: total, per_page: pageSize, page: current,  results: articleList } = useSelector(state => state.article)
  useEffect(() => {
    dispatch(getArticles())
  }, [dispatch])

  const del = async (id) => {
    // 确认是否删除
    console.log('要删除的id', id)
    await dispatch(delArticle(id))

    // 重新获取数据
    dispatch(getArticles(paramsRef.current))
    message.success('删除成功')
  }

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'name',
      render(data){
        return ( data.type > 0 ? <Image
          width={100}
          height={100}
          src={data.images[0]}
          fallback={defaultImg}
        /> : <Image
          width={100}
          height={100}
          src="error"
          fallback={defaultImg}/>)
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'age'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'address',
      render(data){

        // -1： 全部，  0： 草稿 ，1：待审核， 2：审核通过，3：审核失败
        return  <Tag color={COLORS[data]}>{STATUS[data]}</Tag> 
        // if(data === 2) {
        //   return '审核通过'
        // } else if(data === 0) {
        //   return '草稿'
        // } else if(data === 1) {
        //   return '待审核'
        // }
        // return '后端给的值：' + data
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count'
    },
    {
      title: '操作',
      dataIndex: 'id',
      render(data) {
        console.log("操作", data)
        return (<Space size="small">
        <Button onClick={ () => history.push('/home/publish/'+ data) } type="primary" shape="circle" icon={<EditOutlined />} />
        {/* <Button onClick={ () => history.push('/home/publish?id='+ data) } type="primary" shape="circle" icon={<EditOutlined />} /> */}
        <Popconfirm title="确定要删除该文章吗？" onConfirm={() => del(data)}>
          <Button type="primary" shape="circle" danger icon={<DeleteOutlined />} />
        </Popconfirm>
        </Space>
        )
      }
    }
  ]
  const paramsRef = useRef({})
  const onFinish = (values) => {
    console.log('收集表单的数据', values)
    // 1. 收集表单的数据
    const params = {
      status: values.status,
      channel_id:values.channel_id,
      page: 1,
      per_page: 10
    }
    if(values.date) {
      params.begin_pubdate = values.date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
      params.end_pubdate = values.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
    }
    console.log(params)
    paramsRef.current = params
    // 2. 发请求
    dispatch(getArticles(params))
  }
  // 分页发请求
  // 在之前的请求的基础上，改了两个参数
  const onChange = (page, per_page) => {
    const params = paramsRef.current
    console.log('onChange', params)
    console.log(page, per_page)
    
    // 重发请求
    dispatch(getArticles({ ...params, page, per_page }))
  }

  return (
    <div className={styles.root} >
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form onFinish={onFinish} initialValues={{ status: undefined }}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={undefined}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            {/*
              如果组件被包在Form.Item中，则，Form.item会自动传入:
                (1) 受控属性value
                (2) onChange事件。
            在组件内部使用 value和onChange 完成受控动作*/}
            {/* <Select placeholder="请选择频道" style={{ width: 200 }}>
          {channelList.map(it => (<Select.Option key={it.id} value={it.id}>{it.name}</Select.Option> ))}
      </Select> */}
            <MyChannels/>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>

      {/* 表格区域 */}
      <Card title={"根据筛选条件共查询到"+total+"条结果:"} style={{ marginTop: 10 }}>
        <Table dataSource={articleList} columns={columns} rowKey="id" 
          pagination={{pageSize, current, total, onChange}}
        />
      </Card>
    </div>
  )
}
